package com.sx.micowell.framework.model

import android.content.Context
import androidx.core.util.Consumer
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.example.mvvm.base.data.MutableLiveListData
import com.example.mvvm.base.vm.BaseViewModel
import com.example.mvvm.rx.RxTimer
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.SPUtils
import com.github.mikephil.charting.data.Entry
import com.miloyu.modelnet.network.ApiResponse
import com.miloyu.modelnet.network.HttpClient
import com.miloyu.modelnet.network.service.IApiService
import com.miloyu.modelnet.network.tools.RxUtils
import com.miloyu.modelnet.request.SportEndBeanItem
import com.miloyu.modelnet.response.SportEndResponse
import com.sx.micowell.framework.app.MyApplication
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.entity.ActionContainer
import com.sx.micowell.framework.entity.SportChangeData
import com.sx.micowell.framework.entity.SportChartPack
import com.sx.micowell.framework.serialPort.ByteUtil
import com.sx.micowell.framework.tools.CalcuUtils
import com.sx.micowell.framework.tools.cmd.CmdUntil
import com.sx.micowell.module.sport.MovementModel
import com.sx.micowell.module.sport.SportReceive
import com.sx.widget.view.CountDownUtils
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableEmitter
import io.reactivex.FlowableOnSubscribe
import io.reactivex.schedulers.Schedulers
import java.lang.Exception
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * @Description 运动
 * @Author 梁浩文
 * @Date 2021/9/1 17:16
 */
class Sport2Model : BaseViewModel() {
    var mode: Int = 1053;

    var lineListData = mutableListOf<Entry>()  //线性图

    var powerLiveData: MutableLiveData<Int> = MutableLiveData()

    var errorFinishEvent: MutableLiveData<Boolean> = MutableLiveData()

    var consumeTime: Long = 0   //总时长

    var uiConsumeTime: MutableLiveData<String> = MutableLiveData<String>("00:00:00")

    var sendEvent = MutableLiveData<Long>()

    var sportList: MutableList<MovementModel> = mutableListOf()

    var currentPosition: MutableLiveData<Int> = MutableLiveData()

    var sportDataUi: MutableLiveData<SportChangeData> = MutableLiveData()

    var pauseSport = true

    //TODO
    var sendEmitter: FlowableEmitter<SportReceive>? = null

    var lineData: MutableLiveData<SportChartPack> = MutableLiveData()



    fun startCache(context: Context) {
        sportList.forEach {
            MyApplication.instance().getProxy(context)
                ?.getProxyUrl(it.url)
        }

    }

    fun finishSport() {
        context.startContainerFragment(
            RouteManager.getInstance()
                .getSportEndFragment("111", "111")
        )
        context.finish()
        /* HttpClient.instance.create(IApiService::class.java)
             .sportEnd(placeConsumeCalories.values.toList())
             .compose(RxUtils.compose())
             .doOnSubscribe {
                 ui.showDialog()
             }
             .subscribe(object : ApiResponse<SportEndResponse>() {
                 override fun success(data: SportEndResponse?, msg: String?) {
                     ui.hideDialog()
                     context.startContainerFragment(
                         RouteManager.getInstance()
                             .getSportEndFragment(data!!.calorie, data.duration)
                     )
                     context.finish()
                 }

                 override fun onFail(e: Throwable?, errorMsg: String?) {
                     ui.hideDialog()
                     errorFinishEvent.postValue(true)
                 }

             })*/
    }


    fun stopSport() {
        pauseSport = true
    }

    fun resumeSport() {
        pauseSport = false

    }

    fun getMode(categoryCmd: Int, fzCategoryCmd: Int): Int {
        var setBit =
            if (fzCategoryCmd == 0) {
                ByteUtil.SetBitZero(categoryCmd, 3)
            } else {
                ByteUtil.SetBit(categoryCmd, 3)
            }
        return setBit
    }

    //获取kg
    fun getPower(): MutableList<Int> {
        var power = powerLiveData.value as Int * 10
        //转换高低位
        var short = ByteUtil.getShort(ByteUtil.getTenToHex(power))
        var low8 = short.substring(0, 2)
        var height8 = short.substring(2, 4)
        var mutableListOf = mutableListOf<Int>()
        mutableListOf.add(ByteUtil.hexStrToTenInteger(height8))
        mutableListOf.add(ByteUtil.hexStrToTenInteger(low8))
        return mutableListOf;
    }

    //叠加卡路里
    fun cacheCalories(calories: Int) {
        var countCalories = CmdUntil.countCalories(calories)
    }

    var rxTimer = RxTimer()
    var serialTimer = RxTimer()
    override fun registerRxBus() {
        super.registerRxBus()
        LogUtils.i("interval")
        rxTimer.interval(1000, object : RxTimer.RxAction {
            override fun action(number: Long) {
                LogUtils.i("interval")
                if (!pauseSport) {
                    consumeTime += 1
                    var time = CountDownUtils.initData(consumeTime)
                    uiConsumeTime.value = time
                }

            }
        })
        serialTimer.interval(500, object : RxTimer.RxAction {
            override fun action(number: Long) {
                sendEvent.value = number
            }

        })
        addSubscribe(
            Flowable.create(object : FlowableOnSubscribe<SportReceive> {
                override fun subscribe(emitter: FlowableEmitter<SportReceive>) {
                    sendEmitter = emitter
                }

            }, BackpressureStrategy.DROP)
                .buffer(150, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.computation())
                .subscribe(object : io.reactivex.functions.Consumer<List<SportReceive>> {
                    override fun accept(t: List<SportReceive>) {
                        if(t.size>0&&!pauseSport){
                            try {
                                //力量模式
                                var format =
                                    SimpleDateFormat("MM:ss").format(Date(System.currentTimeMillis()))
                                var xLabelList = mutableListOf<String>()
                                var yValue = mutableListOf<Int>()
                                var cal =0
                                t.forEach {
                                    cal+=CmdUntil.countCalories(it.power).toInt()
                                    when (mode) {
                                        1053 -> {
                                            //观察者模式 时间-力矩
                                            xLabelList.add(format)
                                            yValue.add(it.moment)
                                        }
                                        1017 -> {
                                            //极限挑战模式 速度-力矩
                                            xLabelList.add(it.speed.toString())
                                            yValue.add(it.moment)
                                        }
                                        1034 -> {
                                            //力量递减模式
                                            xLabelList.add(it.count.toString())
                                            yValue.add(it.moment)
                                        }
                                        1035 -> {
                                            //链条模式 时间-力矩
                                            xLabelList.add(format)
                                            yValue.add(it.moment)
                                        }
                                        1036 -> {
                                            //高尔夫模式 速度-力矩
                                            xLabelList.add(it.speed.toString())
                                            yValue.add(it.moment)
                                        }
                                        1037 -> {
                                            //划船模式 速度-力矩
                                            xLabelList.add(it.speed.toString())
                                            yValue.add(it.moment)
                                        }
                                        1057 -> {
                                            //力量递增模式
                                            xLabelList.add(it.count.toString())
                                            yValue.add(it.moment)
                                        }
                                        1048 -> {
                                            //恒等张力 时间-速度
                                            xLabelList.add(format)
                                            yValue.add(it.speed)
                                        }
                                    }
                                }
                                lineData.postValue(SportChartPack(xLabelList, yValue,cal))
                            } catch (e: Exception) {

                            }
                        }

                    }
                }, object : io.reactivex.functions.Consumer<Throwable> {
                    override fun accept(t: Throwable?) {

                    }
                })
        )

    }

    fun onNext(body: SportReceive) {
        if (sendEmitter?.isCancelled == false) {
            sendEmitter?.onNext(body)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        rxTimer?.let {
            it.cancel()
        }
        serialTimer?.let {
            it.cancel()
        }
    }
}

